<template>
	<view class="content">
		<u-navbar title="高级实名认证" :bg-color="`${mainColor}`" fixed placeholder autoBack :height="navigationBarHeight"
			:title-style="{color:`${textColor}`, fontSize:'16px', fontWeight:700}"
			:left-icon-color="`${textColor}`" 
			v-if="showTitle"/>

		<view class="main">
			<view class="title">
				请拍摄并上传你的身份证照片
			</view>
			<view class="card-box">
				<view class="txt">
					拍摄正面<text style="color: #e33233;">（人像面）</text>
				</view>
				<image class="card-boder" :src="baseUrl(card.front)" v-if="card.front" @click="clickCard('front')">
				</image>
				<view class="card-boder" v-else @click="clickCard('front')">
					<u-icon name="plus" size="30" color="#606266"></u-icon>
				</view>
			</view>
			<view class="card-box">
				<view class="txt">
					拍摄背面<text style="color: #e33233;">（国徽面）</text>
				</view>
				<image class="card-boder" :src="baseUrl(card.back)" v-if="card.back" @click="clickCard('back')"></image>
				<view class="card-boder" v-else @click="clickCard('back')">
					<u-icon name="plus" size="30" color="#606266"></u-icon>
				</view>
			</view>
		</view>
		<view class="fix-bottm" :style="{bottom:`${bottomHeight}px`}">
			<u-button :color="`${mainColor}`" shape="circle" @click="doSubmit"
				:custom-style="{color: `${textColor}`}">提交</u-button>
		</view>
	</view>
</template>

<script>
	import {
		systemInfo
	} from '@/utils/mixin';
	import {
		baseUrl,
		uploadImage,
		doAdvanceAuth
	} from '@/api'

	export default {
		mixins: [systemInfo],
		data() {
			return {
				baseUrl,
				card: {
					front: null,
					back: null
				}
			}
		},
		onLoad() {
			this.getSystemInfo();
		},
		methods: {
			clickCard(type) {
				const card = this.card;
				uni.chooseImage({
					count: 1,
					success: async ({
						tempFiles,
						tempFilePaths
					}) => {
						console.log("原始图片大小:", tempFiles[0].size / 1024, "KB");
						uni.showLoading({
							title: '图片上传中'
						});
						this.compressImage(tempFilePaths[0], async (tempFilePath) => {
							const res = await uploadImage(tempFilePath)
							uni.hideLoading();
							if (res.code === 2000) {
								if (type == 'front') {
									card.front = res.data.url
								} else if (type == 'back') {
									card.back = res.data.url
								}
							}
						})
					}
				})
			},
			async doSubmit() {
				if (!this.card.front) {
					this.notify('请提供身份证正面图片！');
				}
				if (!this.card.back) {
					this.notify('请提供身份证背面图片！');
				}
				uni.showLoading({
					title: '认证中'
				});
				const res = await doAdvanceAuth(this.card.front, this.card.back);
				uni.hideLoading();
				if (res.code === 2000) {
					this.setToast(res.msg);
					uni.navigateBack();
				} else {
					card.front = null;
					card.back = null;
				}
			},
			notify(message) {
				uni.showToast({
					icon: 'none',
					title: message
				})
			},
			compressImage(path, callback) {
				// #ifdef H5
				this.compressImageH5(path).then((tempFilePath) => {
					console.log('压缩后图片路径：', tempFilePath);
					callback(tempFilePath);
				}).catch((res) => {
					console.log('图片压缩失败！', res);
					uni.hideLoading();
				})
				// #endif

				// #ifndef H5
				uni.compressImage({
					src: path,
					quality: 70, // 压缩质量 0-100
					success: ({
						tempFilePath
					}) => {
						console.log('压缩后图片路径：', tempFilePath);
						callback(tempFilePath);
					},
					fail() {
						console.log('图片压缩失败！');
						uni.hideLoading();
					}
				});
				// #endif

			},
			async compressImageH5(path, quality = 0.7, maxWidth = 800) {
				const res = await fetch(path);
				const blob = await res.blob();
				return new Promise((resolve, reject) => {
					const reader = new FileReader();
					reader.readAsDataURL(blob);

					reader.onload = (e) => {
						const img = new Image();
						img.src = e.target.result;

						img.onload = () => {
							const canvas = document.createElement('canvas');
							const ctx = canvas.getContext('2d');

							// 按宽度等比例缩放
							const scale = Math.min(1, maxWidth / img.width);
							canvas.width = img.width * scale;
							canvas.height = img.height * scale;

							ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

							const compressedUrl = canvas.toDataURL('image/jpeg', quality);
							resolve(compressedUrl);
						};

						img.onerror = reject;
					};

					reader.onerror = reject;
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		padding: 20px;

		.title {
			margin-bottom: 20px;
		}

		.card-box {
			margin-bottom: 20px;

			.txt {
				color: #666;
				font-size: 14px;
				margin-bottom: 20px;
			}

			.card-boder {
				position: relative;
				width: 100%;
				height: 156px;
				line-height: 156px;
				border: 1px solid #e4e4e4;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.fix-bottm {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10px;
		box-sizing: border-box;
	}
</style>